<script setup lang="ts">
import { ref, reactive, watch, onMounted, defineProps } from "vue";
import ReCol from "@/components/ReCol";
import { formRules } from "./utils/rule";
import { message } from "@/utils/message";
import { formProps, type FormInstance } from "element-plus";
import AddCoordinate from "@/components/AddCoordinate/index.vue";
import { useMapStoreHook } from "@/store/modules/map";
import { GetAllStation } from '@/utils/api/dispatch/station'
import { PureTableBar } from "@/components/RePureTableBar";
import { useCrossDept } from "./utils/crossHook";
import { getCross } from '@/utils/api/dispatch/cross'
import { taskareaList, taskareaAdd, taskareaUpdate, taskareaDel, getTaskarea } from '@/utils/api/dispatch/jobRegion'
import { GetAllAgv } from '@/utils/api/dispatch/agv'
import { cloneDeep } from "lodash";
import Konva from "konva";
import { useDept } from "./utils/hook";
import { wareList } from '@/utils/api/BasicManagement/warehouse'

const warehouseList = ref([]);
const getWareList = () => {
    wareList().then(({ Content: { Results } }) => {
        warehouseList.value = Results
    })
}

const pureMap = useMapStoreHook()

interface Props {
    formInline?: any,
    isUpdate?: boolean
}

const props = withDefaults(defineProps<Props>(), {
    isUpdate: false
});

const ruleFormRef = ref();
const newFormInline: { [key: string]: any; } = ref({
    name: "",
    status: 1,
    stationList: [{}],
    agvNameList: [],
    priority: 1,
    note: "",
    type: 1,
    warehouseid: null,
    floor: null,
    tasknum: null
});
const isUpdate = ref(props.isUpdate);
const agvOptions = ref([]);
const {
    columns,
    loading,
    dataList,
    onSearch,
    pagination,
} = useCrossDept();

function getRef() {
    return ruleFormRef.value;
}

function crossNameChange(val) {
    pureMap.$patch((state) => {
        state.crossDetail.name = val
    })
}

function chores(title, data) {
    message(`${title}成功`, {
        type: "success"
    });
    pureMap.targetCross.name(`job-${pureMap.crossDetail.name}`)
    // pureMap.targetCross.attrs.type = 1
    onSearch()
    pureMap.$patch({
        crossSwitch: false
    })
    isUpdate.value = false
    resetForm(ruleFormRef.value)
}

/**
 * 新增
*/
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            var data = newFormInline.value
            if (data.type === 2) {
                //将data里的floor字段转换为数字类型
                data.floor = Number(data.floor)
                data.tasknum = Number(data.tasknum)
            } else {
                data.floor = 0
                data.tasknum = 0
                data.warehouseid = 0
            }
            if (data.type === 3 || data.type === 5) {
                data.agvids = null
                data.agvNameList = null
            } else {
                data.agvNameList = []
                newFormInline.value?.agvids?.forEach(v => {
                    data.agvNameList.push(agvOptions.value.find(item => item.AgvId === v)?.AgvName)
                })
                data.agvids = newFormInline.value?.agvids?.toString()
            }
            //如果不是number类型就提示
            if (isNaN(data.floor)) {
                message('请输入正确的楼层', {
                    type: "error"
                });
                newFormInline.value.floor = null
                return
            }
            if (isUpdate.value) {
                taskareaUpdate(data).then(res => {
                    if (res.Code === 0) chores('修改', data)
                    // pureMap.targetCross.children.forEach(v=>{
                    //   if(v.name() === 'circle'){
                    //     v.fill('red')
                    //   }else{
                    //     v.stroke('red')
                    //   }
                    // })
                })
            } else {
                taskareaAdd(data).then(res => {
                    if (res.Code === 0) {
                        chores('新增', data)
                    }
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    connect()
    isUpdate.value = false

    if (isUpdate.value) {
        pureMap.targetCross.destroy()

        pureMap.targetCross.children.forEach(v => {
            if (v.name() === 'circle') {
                v.fill('red')
            } else {
                v.stroke('red')
            }
        })
    }
}

// 编辑
async function crossUpdate(id: number) {
    let { Content } = await getTaskarea(id)
    // console.log('编辑=>', Content);

    newFormInline.value = Content
    newFormInline.value.agvids = newFormInline.value?.agvids?.split(',').map(v => { return Number(v) })
    for (let key in pureMap.crossDetail) {
        pureMap.$patch((state) => {
            state.crossDetail[key] = Content[key]
        })
    }
    isUpdate.value = true

    pureMap.getCross(pureMap.stageKonva.find(`.job-${pureMap.crossDetail.name}`)[0])
}

// 关联form与pureMap
function connect() {
    Object.keys(pureMap.crossDetail).forEach(v => {
        pureMap.$patch((state) => {
            state.crossDetail[v] = newFormInline.value[v]
        })
    })
}

onMounted(async () => {
    // 站点下拉
    const { Content } = await GetAllAgv()
    agvOptions.value = Content

    connect()

    getWareList()
})


defineExpose({ getRef, crossUpdate, resetForm });
</script>

<template>
    <el-form ref="ruleFormRef" :model="newFormInline" :rules="formRules" label-width="50px">
        <el-row :gutter="30">
            <re-col :value="12" :xs="24" :sm="24">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="newFormInline.name" size="small" clearable placeholder="请输入名称"
                        @change="crossNameChange" />
                </el-form-item>
            </re-col>
            <re-col :value="12" :xs="24" :sm="24">
                <el-form-item label="状态" prop="status">
                    <el-select v-model="newFormInline.status" size="small" placeholder="请选择状态" style="width:100%">
                        <el-option label="启用" :value="1" />
                        <el-option label="禁用" :value="0" />
                        <el-option label="锁定" :value="2" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24">
                <el-form-item label="类型" prop="type">
                    <el-select v-model="newFormInline.type" size="small" placeholder="请选择区域类型" style="width:100%">
                        <el-option label="任务区域" :value=1 />
                        <el-option label="楼层" :value=2 />
                        <el-option label="载货可旋转区域" :value=3 />
                        <el-option label="掉头区域" :value=5 />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 1 || newFormInline.type === 2">
                <el-form-item label="车辆" prop="agvids">
                    <el-select v-model="newFormInline.agvids" size="small" multiple placeholder="请选择车辆"
                        style="width:100%">
                        <el-option v-for="item in agvOptions" :key="item.AgvId" :label="item.AgvName"
                            :value="item.AgvId" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 1 || newFormInline.type === 2">
                <el-form-item label="规则" prop="priority">
                    <el-select v-model="newFormInline.priority" size="small" placeholder="请选择任务派发规则" style="width:100%">
                        <el-option label="随机派发" :value="1" />
                        <el-option label="车辆顺序派发" :value="2" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 2">
                <el-form-item label="仓库" prop="warehouseid">
                    <el-select v-model="newFormInline.warehouseid" size="small" placeholder="请选择仓库" style="width:100%">
                        <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 2">
                <el-form-item label="楼层" prop="floor">
                    <el-input v-model="newFormInline.floor" size="small" clearable placeholder="请输入楼层" />
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 2">
                <el-form-item label="借调任务数量" prop="tasknum" label-width="100px">
                    <el-input v-model="newFormInline.tasknum" size="small" clearable placeholder="请输入借调任务数量" />
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24">
                <el-form-item label="区域" prop="stationList" style="font-weight: 700;">
                    <Add-coordinate :data="newFormInline.stationList"></Add-coordinate>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24">
                <el-form-item label="备注" prop="note">
                    <el-input v-model="newFormInline.note" size="small" clearable placeholder="请输入备注" type="textarea" />
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24">
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                    <el-button type="danger" @click="resetForm(ruleFormRef)">清空数据</el-button>
                </el-form-item>
            </re-col>
        </el-row>
    </el-form>

    <!-- <PureTableBar title="交管列表" :columns="columns" size="small" @refresh="onSearch">
      <template v-slot="{ size, dynamicColumns }">
        <pure-table ref="tableRef" adaptive align-whole="center" row-key="Id" showOverflowTooltip table-layout="auto"
          :loading="loading" :size="size" :data="dataList" :columns="dynamicColumns" :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false" :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }">
          <template #operation="{ row }">
            <el-button class="reset-margin" :size="size" link type="primary" @click="crossUpdate(row.id)">
              编辑
            </el-button>
          </template>
</pure-table>
</template>
</PureTableBar> -->
</template>

<style lang="scss" scoped>
.el-radio {
    margin-right: 16px;
}
</style>
